<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">当当书城</h3>
      </div>
      <!-- 用户名 -->
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账号"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        :disabled="disableLogin"
        @click.native.prevent="handleLogin"
        >{{ loginIn }}</el-button
      >

      <div class="tips">
        <el-checkbox v-model="checked" style="color: #fff">记住我</el-checkbox>
        <a href="#/login">已有账号？去注册</a>
      </div>
    </el-form>
  </div>
</template>

<script>
import { notify } from "@/utils/message";

export default {
  name: "Regist",
  data() {
    // 验证用户名
    const validateUsername = (rule, value, callback) => {
      if (!/^[a-zA-Z0-9_]{3,}$/.test(value)) {
        this.usernameValid = false;
        callback(new Error("用户名由数字、字母、下划线组成、不少于3位数。"));
      } else {
        this.usernameValid = true;
        callback();
      }
    };
    // 验证密码
    const validatePassword = (rule, value, callback) => {
      if (!/^[a-zA-Z0-9_]{3,}$/.test(value)) {
        callback(new Error("密码由数字、字母、下划线组成、不少于3位数。"));
        this.pwdValid = false;
      } else {
        callback();
        this.pwdValid = true;
      }
    };
    return {
      // 登录数据
      loginForm: {
        username: "",
        password: "",
      },
      checked: false, // 是否勾选记住我
      // 是否允许登录
      usernameValid: false,
      pwdValid: false,
      disableLogin: true, // 是否禁止登录
      loginIn: "注册", // 登录文字
      // 登录规则
      loginRules: {
        username: [
          { required: true, trigger: "change", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "change", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: "/login", // 注册成功时重定向的路径
    };
  },
  // 计算变化
  computed: {
    validateLogin() {
      return this.usernameValid && this.pwdValid;
    },
  },
  // 监听属性
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
    validateLogin(val) {
      this.disableLogin = !val;
    },
  },
  methods: {
    // 点击展示密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    // 处理注册业务
    handleLogin() {
      // 当符合规则时发送请求
      this.$refs.loginForm.validate((valid) => {
        const text = "注册";
        if (valid) {
          this.loginIn = "注册中";
          this.loading = true; // 开启加载中动画，并修改"登录"为"登录中"
          setTimeout(() => {
            this.loading = false;
            // 发送请求
            this.$store
              .dispatch("user/regist", this.loginForm)
              .then((res) => {
                if (res.data.code == -1) {
                  notify(2, text, "注册失败，用户名已存在");
                  return;
                }
                notify(1, text, "正在跳转登录页面");
                setTimeout(() => {
                  this.$router.push({ path: this.redirect || "/login" });
                }, 2000);
              })
              .catch((err) => {
                console.log(err);
                notify(2, text, "注册失败，网络连接超时");
              });
            this.loginIn = text;
          }, 1200);
        } else {
          notify(2, text, "您输入的账号或密码格式不正确 ~");
        }
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #234167; // #283443 默认
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>
<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  // 提示
  .tips {
    // 使用弹性布局进行两边分散
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    // 去注册
    a:hover {
      color: #409eff;
      text-decoration: underline;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
